package org.jeecg.modules.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.common.DateCommon;
import org.jeecg.modules.entity.*;
import org.jeecg.modules.entity.vo.DbProjectVo;
import org.jeecg.modules.mapper.DbFileMapper;
import org.jeecg.modules.mapper.DbProjectMapper;
import org.jeecg.modules.mapper.DbSeqMapper;
import org.jeecg.modules.service.IDbContractService;
import org.jeecg.modules.service.IDbFileService;
import org.jeecg.modules.service.IDbProjectService;
import org.jeecg.modules.service.IDbSeqService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: db_project
 * @Author: jeecg-boot
 * @Date:   2024-06-26
 * @Version: V1.0
 */
@Service
public class DbProjectServiceImpl extends ServiceImpl<DbProjectMapper, DbProject> implements IDbProjectService {


    @Autowired
    private IDbFileService dbFileService;
    @Autowired
    private IDbSeqService dbSeqService;
    @Autowired
    private IDbContractService dbContractService;
    /**
     * 插入项目及附件
     * @param dbProject
     */
    @Transactional
    public boolean add(DbProject dbProject) {
        //编号生成
        DbSeq dbSeq = new DbSeq();
        QueryWrapper<DbSeq> queryWrapper = new QueryWrapper<>();
        Date currentDate = new Date();
        String formattedDate = DateCommon.YYYYMMDD.format(currentDate);
        String name = "db_project"+formattedDate;
        queryWrapper.eq("name",name);
        DbSeq dbSeq1 = dbSeqService.getOne(queryWrapper);
        if(dbSeq1 == null){
            dbSeq.setName(name);
            dbSeq.setSeq(0001);
            String projectId=formattedDate+"0001";
            dbSeqService.save(dbSeq);
            dbProject.setCode(projectId);
            //插入file_group_id
            boolean b = updateFileGroupId(dbProject);
            return b;
        }else{
            Integer seq = dbSeq1.getSeq();
            seq+=1;
            UpdateWrapper<DbSeq> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("seq",seq).eq("name",dbSeq1.getName());
            dbSeqService.update(dbSeq1,updateWrapper);
            // 使用String.format()来确保序列号是4位数，不足的前面补0
            String seqStr = String.format("%04d", seq);
            String projectId=formattedDate+seqStr;
            dbProject.setCode(projectId);
            //插入file_group_id
            boolean b = updateFileGroupId(dbProject);
            return b;
        }
    }

    /**
     * 更新文件信息
     * @param dbProject
     */
    @Transactional
    public void updateAndFileById(DbProject dbProject) {
        if(dbProject.getFileIds()==null||dbProject.getFileIds().isEmpty()){
            this.updateById(dbProject);
        }else {
            dbProject.setFileGroupId(null);
            this.updateById(dbProject);
            UpdateWrapper<DbProject> projectUpdateWrapper = new UpdateWrapper<>();
            String fileGroupId = "db_project"+dbProject.getCode();
            projectUpdateWrapper.set("file_group_id",fileGroupId).eq("id",dbProject.getId());
            this.update(dbProject,projectUpdateWrapper);
            UpdateWrapper<DbFile> updateWrapper = new UpdateWrapper<>();
            DbFile dbFile = new DbFile();
            updateWrapper.set("group_id", fileGroupId).in("id",dbProject.getFileIds());
            dbFileService.update(dbFile,updateWrapper);
        }
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @Transactional
    public void deleteById(String id) {
        DbProject dbProject = this.getById(id);
        if(dbProject.getFileGroupId()!=null){
            QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",dbProject.getFileGroupId());
            List<DbFile> list = dbFileService.list(queryWrapper);
            list.forEach(dbFile -> {
                dbFileService.removeById(dbFile.getId());
            });
        }
        this.removeById(id);
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @Transactional
    public void deleteBatch(String ids) {
        //批量删除文件
        List<String> idList= Arrays.asList(ids.split(","));
        idList.forEach(id -> {
            DbProject dbProject = this.getById(id);
            if(dbProject.getFileGroupId()!=null){
                QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("group_id",dbProject.getFileGroupId());
                List<DbFile> list = dbFileService.list(queryWrapper);
                list.forEach(dbFile -> {
                    dbFileService.removeById(dbFile.getId());
                });
            }
        });
        this.removeByIds(idList);
    }
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    public DbProjectVo queryById(String id) {
        DbProject dbProject = this.getById(id);
        if(dbProject==null) {
            return null;
        }
        DbProjectVo dbProjectVo = new DbProjectVo();
        QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
        BeanUtils.copyProperties(dbProject,dbProjectVo);
        //查找文件路径和id
        if(dbProject.getFileGroupId()!=null){
            String fileGroupId = dbProject.getFileGroupId();
            queryWrapper.eq("group_id",fileGroupId);
            List<DbFile> list = dbFileService.list(queryWrapper);
            List<String> dbFileList = new ArrayList<>();
            List<String> dbFileIds = new ArrayList<>();
            list.forEach(dbFile -> {
                dbFileList.add(dbFile.getFilePath());
                dbFileIds.add(dbFile.getId());
            });
            dbProjectVo.setFilePaths(dbFileList);
            dbProjectVo.setFileIds(dbFileIds);
        }
        return dbProjectVo;
    }

    private boolean updateFileGroupId(DbProject dbProject){
//        判断合同id是否存在
        String contractId = dbProject.getContractId();
        if(contractId!=null){
            DbContract contract = dbContractService.getOne(new QueryWrapper<DbContract>().eq("contract_id", contractId));
            if(contract==null){
                return false;
            }
        }
        if(dbProject.getFileIds()==null||dbProject.getFileIds().isEmpty()){
            this.save(dbProject);
            return true;
        }else {
            dbProject.setFileGroupId(null);
            this.save(dbProject);
            UpdateWrapper<DbProject> dbProjectUpdateWrapper = new UpdateWrapper<>();
            String fileGroupId = "db_project"+dbProject.getCode();
            dbProjectUpdateWrapper.set("file_group_id",fileGroupId).eq("id",dbProject.getId());
            this.update(dbProject,dbProjectUpdateWrapper);
            UpdateWrapper<DbFile> updateWrapper = new UpdateWrapper<>();
            DbFile dbFile = new DbFile();
            updateWrapper.set("group_id", fileGroupId).in("id",dbProject.getFileIds());
            dbFileService.update(dbFile,updateWrapper);
            return true;
        }
    }
}
